package br.com.jr.arq.dao;

import java.util.Collection;

import javax.inject.Inject;

import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Expression;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.jr.arq.utils.StringUtils;

@Repository
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)  
public class GenericDao {

	@Inject
	protected HibernateTemplate ht;
	
	protected static final int INSERIR = 1;
	protected static final int ATUALIZAR = 2;
	protected static final int REMOVER = 3;
	
	public void change( Object obj, int operacao){
		switch ( operacao ) {
		case INSERIR:
		case ATUALIZAR:
			ht.saveOrUpdate(obj);
			break;

		case REMOVER:
			ht.delete(obj);
			break;
		}
	}

	public void create( Persistente persistente ) throws Exception  {
		change( persistente, 1 );
	}
	public void remove( Persistente persistente  ) throws Exception  {
		change( persistente, 3 );
	}
	public void update( Persistente persistente ) throws Exception  {
		change( persistente, 2 );
	}

	public <T> Collection<T> findAll( Class<T> classe ) throws Exception {
			return ht.loadAll(classe);
	}

	public <T extends Persistente> T findByPrimaryKey( int id, Class<T> classe ) throws Exception {
		return  ht.get( classe, id );
	}

	@SuppressWarnings("unchecked")
	public <T> Collection<T> findByLike(Class<T> classe, String campo, String valor){
		DetachedCriteria dc = DetachedCriteria.forClass(classe);
		dc.add(Expression.like(campo, StringUtils.toAscii(valor).toUpperCase() + "%"));
		return ht.findByCriteria(dc);
	}

	@SuppressWarnings("unchecked")
    public <T> Collection<T> findByEq(Class<T> classe, String campo, boolean valor){
		DetachedCriteria dc = DetachedCriteria.forClass(classe);
		dc.add(Expression.eq(campo, valor));
		return ht.findByCriteria(dc);
	}
	
	public Session getSession() {
		return ht.getSessionFactory().openSession();
	}

}